{% extends 'layout/manage.html' %}
{% load issues %}
{% load static %}

{% block css %}
    <link rel="stylesheet" href="{% static 'plugin/editor-md/css/editormd.min.css' %}">

    {#    时间选择框#}
    <link rel="stylesheet" href="{% static 'plugin/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    {#    bootstrap选择框#}
    <link rel="stylesheet" href="{% static 'plugin/bootstrap-select/css/bootstrap-select.min.css' %}">
    <style>
        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #ddd;
            color: black;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }

        .issues-list .number {
            width: 100px;
            text-align: right;
        }

        .issues-list .number a {
            font-weight: 500;
            padding: 0 10px;
        }

        .issues-list .issue .tags {
            padding: 10px 0;
        }

        .issues-list .issue .tags span {
            margin-right: 20px;
            display: inline-block;
            font-size: 12px;
        }

        .issues-list .issue .tags .type {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dddddd;
        }

    </style>
{% endblock css %}

{% block content %}
    <div class="container clearfix" style="padding: 20px 0;">

        <div class="col-sm-7">
            <div class="panel panel-default" style="margin-top: 0">
                <div class="panel-heading">
                    <i class="fa fa-edit"></i> 更新问题
                </div>
                <div class="panel-body">
                    <form id="addForm" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label class="col-sm-2 control-label"
                                   for="{{ form.issues_type.id_for_label }}">{{ form.issues_type.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.issues_type }}
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"
                                   for="{{ form.subject.id_for_label }}">{{ form.subject.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.subject }}
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"
                                   for="{{ form.module.id_for_label }}">{{ form.module.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.module }}
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"
                                   for="{{ form.desc.id_for_label }}">{{ form.desc.label }}</label>
                            <div class="col-sm-10">
                                <div id="editor">
                                    {{ form.desc }}
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>

                        <div class="form-group clearfix">

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 clearfix">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                            <div class="col-md-6 pd-0">
                                <label for=" {{ form.priority.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.assign.id_for_label }}" class="col-md-4 control-label">指派给</label>
                                <div class="col-md-8">
                                    {{ form.assign }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.attention.id_for_label }}"
                                       class="col-md-4 control-label">关注者</label>
                                <div class="col-md-8">
                                    {{ form.attention }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">开始时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg"></span>

                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">截止时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">模式</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label"> 父问题</label>
                                <div class="col-md-8">

                                    {{ form.parent }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>

                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-sm-5">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 操作记录
                </div>
                <div class="panel-body comment-area">

                    <div class="comment-list">
                    </div>
                    <hr/>
                    <div class="comment-text" id="commentText">

                        <div class="form-group">
                            <textarea id="content" rows="6" class="form-control"
                                      placeholder="请输入要回复的内容"></textarea>
                            <span class="error-msg"></span>
                        </div>
                        <input class="btn btn-primary" type="button" id="btnSubmit" value="提 交">
                        <div class="reply-user hide" id="replyUser">
                            回复 <span></span>
                            <i class="fa fa-times-circle" aria-hidden="true" style="color: #9d9d9d;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="hide" id="recordTemplate">
        <div class="item clearfix">
            <div class="left-avatar"></div>
            <div class="right-info">
                <pre></pre>
                <div class="desc">
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="type"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-user-o" aria-hidden="true"></i>
                        <span class="user"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                        <span class="date"></span>
                    </div>

                    <a href="#commentText" class="reply">
                        <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                    </a>

                </div>
            </div>
            <div class="child">

            </div>
        </div>
    </div>

{% endblock content %}

{% block js %}
    <script src="{% static 'plugin/editor-md/editormd.js' %}"></script>
    {#    时间选择框#}
    <script src="{% static 'plugin/bootstrap-datepicker/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>

    {#    bootstrap选择框#}
    <script src="{% static 'plugin/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-select/js/i18n/defaults-zh_CN.min.js' %}"></script>

    <script>
        var WIKI_UPLOAD_URL = '{% url 'web:manage:wiki_upload_img' request.tracer.project.id %}';
        var EDITOR;

        $(function () {
            initEditorMd();
            initDatepicker();
            initIssuesRecord();
            bindReply();
            bindCancelReplyUser();
            $('#btnSubmit').click(function () {
                bindSubmit();
            });
            bindAddForm();
        });

        // 问题评论初始化
        function initIssuesRecord() {
            $.ajax({
                url: '{% url 'web:manage:issues_record' request.tracer.project.id issues_obj.id %}',
                type: 'GET',
                dataType: 'json'
            }).done(function (data) {
                console.log((data.msg));
                $.each(data.msg, function (k, v) {
                    createRecordNode(v);
                });
            }).fail(function () {
                console.log("网络连接失败");
            })
        }

        /*
        创建操作记录节点
         */
        function createRecordNode(nodeDict) {
            var $item = $("#recordTemplate").find('.item').clone();
            $item.find('.left-avatar').html(nodeDict.create_user[0].toUpperCase());
            $item.find('pre').html(nodeDict.content);
            $item.find('.user').html(nodeDict.create_user);
            $item.find('.type').html(nodeDict.reply_type_text);
            $item.find('.date').html(nodeDict.datetime);
            $item.attr({id: nodeDict.id, username: nodeDict.create_user});

            if (nodeDict.parent_id) {
                // 挂在谁下
                $('#' + nodeDict.parent_id).children('.child').append($item);
            } else {
                // 根下
                $('.comment-list').append($item);
            }
        }

        /*
        回复问题
         */
        function bindReply() {
            $('.comment-list').on('click', '.reply', function () {
                var $item = $(this).parent().parent().parent();
                var id = $item.attr('id');
                var username = $item.attr('username');
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        /*
        取消回复
         */
        function bindCancelReplyUser() {

            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text("");
            })
        }

        // 评论提交事件
        function bindSubmit() {
            $("#commentText .error-msg").text("");
            $.ajax({
                url: '{% url 'web:manage:issues_record' request.tracer.project.id issues_obj.id %}',
                type: 'POST',
                data: {'content': $('#content').val(), 'reply': $('#replyUser').attr('parent-id')},
                dataType: 'JSON'
            }).done(function (data) {
                if (data.code === 200) {
                    // 添加节点
                    createRecordNode(data.msg);
                    // 输入的内容清空
                    $('#content').val('');
                    $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text("");
                } else {
                    $.each(data.msg, function (k, v) {
                        $('#content').next('.error-msg').text(v[0]);
                    })
                }
            }).fail(function () {
                console.log('网络连接错误');
            })
        }

        // 处理问题修改事件
        function bindAddForm() {
            $('#addForm').find('.form-control').change(function () {
                var Dict = {name: $(this).attr('name'), value: $(this).val()};
                if(Dict.name){
                    postAjaxData(Dict);
                }
            });
        }

        // 处理Markdown保存问题
        function saveMarkdown() {
            var Dict = {name: 'desc', value: EDITOR.getValue()};
            console.log(Dict);
            postAjaxData(Dict);
        }

        // 发送问题修改数据
        function postAjaxData(Dict) {
            $('#id_' + Dict.name).parent().next('.error-msg').text('');
            $.ajax({
                url: '{% url 'web:manage:issues_change' request.tracer.project.id issues_obj.id %}',
                type: 'POST',
                header: {
                    "Content-Type": "application/json;charset=utf-8"
                },
                data: JSON.stringify(Dict),
                dataType: 'JSON'
            }).done(function (data) {
                if (data.code === 200) {
                    // 添加节点
                    createRecordNode(data.msg);
                } else {
                    $('#id_' + Dict.name).parent().next('.error-msg').text(data.msg);
                }
            }).fail(function () {
                console.log('网络连接错误');
            })
        }

        // 初始化时间
        function initDatepicker() {
            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd',
                startDate: '0',
                language: "zh-CN",
                autoclose: true
            });
        }

        // Markdown编辑器的初始化
        function initEditorMd() {
            {#editor是对应编辑页的ID，path是指Markdown文件的依赖其他文件#}
            EDITOR = editormd('editor', {
                placeholder: "请输入内容",
                height: 300,
                {#emoji: true,#}
                path: "{% static 'plugin/editor-md/lib/' %}",

                // 配置Markdown支持文件上传
                imageUpload: true,
                imageFormats: ["jpg", 'jpeg', 'png', 'gif'],
                imageUploadURL: WIKI_UPLOAD_URL,
                toolbarAutoFixed: false,
                toolbarIcons: function () {
                    return ["bold", "hr", "del", "italic", "quote", "|", "image", "preview", "watch", "fullscreen", "||", "save"]
                },
                toolbarCustomIcons: {
                    save: "<input type='button' value='保 存' class='btn btn-success btn-sm' onclick='saveMarkdown();' />"
                },

                // 以预览形式展示
                onload: function () {
                    this.previewing();
                }
            });
        }
    </script>
{% endblock js %}